package vip.xls8z.reactor.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

/**
 * @author jason.tang
 * @date 2021/4/12 16:50
 * @desc
 */

@Slf4j
@RestController
public class HelloController {

    // springmvc
    @GetMapping("/mvc")
    public String mvcSayHello() {
        long time = System.currentTimeMillis();
        log.info("-----mvc start----");
        String uuid = uuid();
        log.info("-----mvc end----, cost: {}ms",System.currentTimeMillis() - time);
        return uuid;
    }

    // web flux, 0 - 1
    @GetMapping("/mono")
    public Mono<String> monoSayHello() {
        long time = System.currentTimeMillis();
        log.info("-----mono start----");
        Mono<String> mono = Mono.fromSupplier(this::uuid);
        log.info("-----mono end----, cost: {}ms",System.currentTimeMillis() - time);
        return mono;
    }

    // web flux, 1 - N
    @GetMapping(value = "/flux", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> fluxSayHello() {
        long time = System.currentTimeMillis();
        log.info("-----flux start----");
        Flux<String> flux = Flux.fromStream(IntStream.range(1, 10).mapToObj(v -> {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "flux str -> " + v + "\n";
        }));
        log.info("-----flux end----, cost: {}ms",System.currentTimeMillis() - time);
        return flux;
    }

    private String uuid() {
        log.info("----get uuid----");
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return UUID.randomUUID().toString();
    }


}
